<?php

namespace app\api\behavior;

use app\admin\model\usermanage\Users;
use app\api\model\GroupPv;
use app\api\model\PvLog;
use app\api\model\shop\Order;
use app\api\model\shop\OrderAction;
use app\api\model\shop\OrderGoods;

use app\common\model\TeamPv;
use think\Db;

class OrderBehavior
{
    public function run(&$response)
    {
        $time = time();

        $pv_settlement_time = \app\common\model\Config::get(['name'=>'pv_settlement_time'])->value;

        if ($pv_settlement_time>0){
            $over_day = $time - ($pv_settlement_time * 3600);
            $npOrder = Order::where(['paystate' => 1,'is_pv' => 0])
                ->where('paytime','>=',$over_day)
                ->where('pv','<>',0)
                ->field('id,user_id,pv')
                ->select();
            foreach ($npOrder as $key => $value){
                $user = Users::get($value['user_id']);
                if ($user){
                    $order_pv_send_sum = PvLog::where([
                        'user_id'=>$value['user_id'],
                        'order_id'=>$value['id'],
                        'type'=>2,
                        'pv_type'=>2,
                    ])->sum('pv');
                    $pv = $value['pv'] - $order_pv_send_sum;

                    if ($pv>0){
                        $pv_log = new PvLog();
                        $pv_log->user_id = $value['user_id'];
                        $pv_log->receive_user_id = 0;
                        $pv_log->setAttr('type',1);
                        $pv_log->pv_type = 1;
                        $pv_log->order_id = $value['id'];
                        $pv_log->pv =  $pv;
                        $pv_log->save();
                        $user->pv += $pv;
                        $user->save();

                        if ($user->group_id){
                            $Areceive_first_group_pv = GroupPv::where(['first_group_id'=>$user->group_id])->select();

                            if (count($Areceive_first_group_pv)>0){
                                foreach ($Areceive_first_group_pv as $k=>$v){
                                    $first_group_pv = GroupPv::get($v['id']);
                                    if ($first_group_pv){
                                        $first_group_pv->first_pv += $pv;
                                        $first_group_pv->updatetime = time();
                                        $first_group_pv->save();
                                    }
                                }
                            }

                            $new_pv = GroupPv::get(['new_group_id'=>$user->group_id]);

                            if ($new_pv){
                                $new_pv->new_pv += $pv;
                                $new_pv->updatetime = time();
                                $new_pv->save();
                            }

                        }

                        //查询团队业绩  发放奖励

                        TeamPv::newTeamPerformance($value['user_id'],1);

                        //上级团队业绩增加
                        if ($user->contact_id>0){
                            $parent_arr = $this->getIds($user->contact_id,[]);

                            foreach ($parent_arr as $item){
                                $superior = Users::get($item);
                                $pv_log = new PvLog();
                                $pv_log->user_id = $item;
                                $pv_log->receive_user_id = 0;
                                $pv_log->setAttr('type',3);
                                $pv_log->pv_type = 1;
                                $pv_log->order_id = $value['id'];
                                $pv_log->pv = $pv;
                                $pv_log->save();
                                $superior->team_pv += $pv;
                                $superior->save();
                                if ($superior->group_id){
                                    $receive_first_group_pv = GroupPv::where(['first_group_id'=>$superior->group_id])->select();
                                    if (count($receive_first_group_pv)>0){
                                        foreach ($receive_first_group_pv as $k=>$v){
                                            $first_group_pv = GroupPv::get($v['id']);
                                            $first_group_pv->first_pv += $pv;
                                            $first_group_pv->save();
                                        }

                                    }
                                    $new_pv = GroupPv::get(['new_group_id'=>$superior->group_id]);
                                    if ($new_pv){
                                        $new_pv->new_pv += $pv;
                                        $new_pv->updatetime = time();
                                        $new_pv->save();
                                    }

                                    //查询团队业绩  发放奖励
                                    TeamPv::newTeamPerformance($item,1);
                                }

                            }
                        }

                        //订单超过未赠送时间，自动结算
                        $value->is_pv = 1;
                        $value->issue_pv_time = time();
                        $value->save();
                    }
                }
            }
        }
        /////订单操作
        //确认收货时间
        $auto_delivery_time = \app\common\model\Config::get(['name'=>'auto_delivery_time'])->value;
        $receive = $time - $auto_delivery_time * 24 * 3600;
        $auto_complete_time = \app\common\model\Config::get(['name'=>'auto_complete_time'])->value;
        $complete = $time - $auto_complete_time * 24 * 3600;
        //失效订单
        $order = Order::where(function ($query) use ($time) {
            $query->where('paystate', 0)->where('expiretime', '<=', $time)->where('orderstate', 0);
        })->whereOr(function ($query) use ($receive) {
            $query->where('shippingstate', 1)->where('paystate', 1)->where('shippingtime', '<=', $receive)->where('orderstate', 0);
        })->whereOr(function ($query) use ($complete) {
            $query->where('shippingstate', 2)->where('paystate', 1)->where('receivetime', '<=', $complete)->where('orderstate', 0);
        })->select();

        //超过设置订单状态为过期
        if ($order) {
            foreach ($order as $item) {
                // 启动事务
                Db::startTrans();
                try {
                    //失效的
                    if (!$item->paystate) {
                        $item->save(['orderstate' => 2]);
                        //库存恢复
                        OrderGoods::setGoodsStocksInc($item->order_sn);

                    } elseif($item->paystate==1&&$item->shippingstate==1) { //待收货的
                        $item->save(['shippingstate' => 2, 'receivetime' => time()]);
                        OrderAction::push($item->order_sn, '系统', '订单确认收货成功');
                    } else {
                        //收货待完成
                        $item->save(['orderstate' => 3]);
                        OrderAction::push($item->order_sn, '系统', '订单已完成');
                    }
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    continue;
                }
            }
        }
    }

    //获取当前用户的所有上级
    public function getIds($id,$arr){
        $parent = Users::get($id);
        array_push($arr,$parent->id);
        if ($parent->contact_id==0){
            return $arr;
        } else {
            return $this->getIds($parent->contact_id,$arr);
        }
    }
}
